// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KukaLBR4CartesianPositionController.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.KukaLBR
{
    using System;
    using System.Collections.Generic;

    using Microsoft.Robotics.Manipulation;
    using Microsoft.Robotics.Manipulation.ControllerStateMachine;
    using Microsoft.Robotics.Numerics;

    using LBR4 = Microsoft.Robotics.Hardware.KukaLBR.KukaLBR4PlusCsharpDefinitionsNativeMethods;

    /// <summary>
    /// A controller for Cartesian position of the TCP of the LBR4
    /// </summary>
    public class KukaLBR4CartesianPositionController : KukaLBR4Controller
    {
        /// <summary>
        /// Controller state machine description cache
        /// </summary>
        private static ControllerStateMachineDescription csmdCache;

        /// <summary>
        /// Determines if we have a cached copy of the controller state machine description available
        /// </summary>
        private static bool haveCachedCsmd = false;

        /// <summary>
        /// Register that stores result of computing commanded Cartesian position 
        /// (i.e. the currently reported Cartesian command with the FRI commanded offset applied
        /// </summary>
        private RegisterID commandedCartesianPositionResultRegister;

        /// <summary>
        /// Register that stores the desired Cartesian position
        /// </summary>
        private RegisterID desiredCartesianPositionRegister;

        /// <summary>
        /// Register that stores the maximum linear speed.
        /// </summary>
        private RegisterID maxLinearSpeedRegister;

        /// <summary>
        /// Register that stores the maximal rotational speed.
        /// </summary>
        private RegisterID maxRotationalSpeedRegister;

        /// <summary>
        /// Register that stores the FRI cycle time.
        /// </summary>
        private RegisterID cycleTimeInMsRegister;

        /// <summary>
        /// Register that stores the value indicating that FRI is in the command state.
        /// </summary>
        private RegisterID friCmdStateValueRegister;

        /// <summary>
        /// Initializes a new instance of the <see cref="KukaLBR4CartesianPositionController"/> class.
        /// </summary>
        /// <param name="registerManager">Manager for assigning working registers.</param>
        /// <param name="desiredPose">Desired Cartesian pose.</param>
        /// <param name="maxLinearSpeedInMetersPerSec">Maximum linear Cartesian speed.</param>
        /// <param name="maxRotationalSpeedInRadPerSec">Maximum rotational Cartesian speed.</param>
        /// <param name="timeStepInMsec">FRI cycle time.</param>
        /// <returns>A set of working registers.</returns>
        public KukaLBR4CartesianPositionController(
            KukaLBR4WorkingRegisterManager registerManager,
            Pose desiredPose,
            double maxLinearSpeedInMetersPerSec,
            double maxRotationalSpeedInRadPerSec,
            double timeStepInMsec) : 
            base(registerManager)
        {
            this.commandedCartesianPositionResultRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Frame));

            this.desiredCartesianPositionRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Frame));

            this.maxLinearSpeedRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

            this.maxRotationalSpeedRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

            this.cycleTimeInMsRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));

             this.friCmdStateValueRegister = RegisterID.NewWorkingRegister(
                this.RegisterManager.GetNextRegisterID(KukaLBR4WorkingRegisterManager.RegisterValueTypes.Scalar));
 
            // CMD state value
            this.WorkingRegisterArray.Registers[this.friCmdStateValueRegister.RegisterNumber][0] = 2;

            double[] destinationFrame = HomogenousTransform.ToFrameArray(HomogenousTransform.CreateFromPose(desiredPose));
            Array.Copy(
                destinationFrame,
                this.WorkingRegisterArray.Registers[this.desiredCartesianPositionRegister.RegisterNumber],
                this.WorkingRegisterArray.Registers[this.desiredCartesianPositionRegister.RegisterNumber].Length);

            this.WorkingRegisterArray.Registers[this.maxLinearSpeedRegister.RegisterNumber][0] = maxLinearSpeedInMetersPerSec;
            this.WorkingRegisterArray.Registers[this.maxRotationalSpeedRegister.RegisterNumber][0] = maxRotationalSpeedInRadPerSec;
            this.WorkingRegisterArray.Registers[this.cycleTimeInMsRegister.RegisterNumber][0] = timeStepInMsec;
        }

        /// <summary>
        /// Builds a state machine controller
        /// </summary>
        /// <returns>A state machine based controller</returns>
        public new ControllerStateMachineDescription BuildStateMachineDescription()
        {
            if (!haveCachedCsmd)
            {
                csmdCache = base.BuildStateMachineDescription();
                haveCachedCsmd = true;
            }

            return csmdCache;
        }

        /// <summary>
        /// Builds a state that synchronizes Cartesian position with FRI.
        /// </summary>
        /// <returns>A controller state machine state.</returns>
        protected static State BuildSynchronizeFRICartesianPositionState()
        {
            ControllerOperation[] operationsList = new ControllerOperation[1];
            RegisterID[] operandsList = new RegisterID[1];

            // Add operation (CopyFrameOp) to copy current measured Cartesian position to commanded Cartesian position.
            // One operand, the current Cartesian position
            operandsList[0] =
                new RegisterID(
                    RegisterTypes.Feedback,
                    (int)LBR4.KukaLBR4PlusFeedbackRegisters.MeasuredCartesianPositionRegister);

            operationsList[0] = new ControllerOperation(
                (int)LBR4.KukaLBR4Operations.CopyFrameOp,
                new RegisterID(
                    RegisterTypes.Working,
                    (int)LBR4.KukaLBR4PlusWorkingRegisters.CartesianPositionCommandRegister),
                operandsList);

            return new State(
                (int)LBR4.ControlModes.CartesianImpedanceControlMode,
                operationsList,
                new Transition[0],
                new Transition[0]);
        }

        /// <summary>
        /// Builds a state that generates a small step in cartesian space towards a desired pose.
        /// </summary>
        /// <param name="commandedCartesianPositionResultRegister">Register containing the frame describing the current Cartesian commanded position.</param>
        /// <param name="desiredCartesianPositionRegister">Register containing frame describing the desired Cartesian position.</param>
        /// <param name="maxLinearSpeedRegister">Register containing the maximum linear Cartesian speed (scalar).</param>
        /// <param name="maxRotationalSpeedRegister">Register containing the maximum rotational Cartesian speed (scalar).</param>
        /// <param name="cycleTimeInMsRegister">Register containing the FRI cycle time (scalar).</param>
        /// <returns>A controller state machine state.</returns>
        protected static State BuildSimpleCartesianInterpolationState(
            RegisterID commandedCartesianPositionResultRegister,
            RegisterID desiredCartesianPositionRegister,
            RegisterID maxLinearSpeedRegister,
            RegisterID maxRotationalSpeedRegister,
            RegisterID cycleTimeInMsRegister)
        {
            // Two operations:
            // 1:  Get the current command by mulitplying the commanded Cartesian position frame
            //     by the commanded Carteisan offset (this is necessitated by the FRI representation of commands)
            // 2:  Set the next Cartesian postion by taking a small step from the currently commanded position
            //     to the goal position
            //
            // Parameters for the interpolation are placed in the following registers:
            // Frame1Register : Desired Cartesian position
            ControllerOperation[] operationsList = new ControllerOperation[2];

            // Operation 1
            RegisterID[] operation1Operands = new RegisterID[2];
            operation1Operands[0] = new RegisterID(
                RegisterTypes.Feedback,
                (int)LBR4.KukaLBR4PlusFeedbackRegisters.CommandedCartesianPositionRegister);
            operation1Operands[1] = new RegisterID(
                RegisterTypes.Feedback,
                (int)LBR4.KukaLBR4PlusFeedbackRegisters.CommandedCartesianOffsetRegister);

            operationsList[0] = new ControllerOperation(
                (int)LBR4.KukaLBR4Operations.MultiplyFramesOp,
                commandedCartesianPositionResultRegister,
                operation1Operands);

            // Operation 2
            RegisterID[] operation2Operands = new RegisterID[5];
            operation2Operands[0] = commandedCartesianPositionResultRegister;
            operation2Operands[1] = desiredCartesianPositionRegister;
            operation2Operands[2] = maxLinearSpeedRegister;
            operation2Operands[3] = maxRotationalSpeedRegister;
            operation2Operands[4] = cycleTimeInMsRegister;

            operationsList[1] = new ControllerOperation(
                (int)LBR4.KukaLBR4Operations.SimpleCartesianInterpolationOp,
                new RegisterID(
                    RegisterTypes.Working,
                    (int)LBR4.KukaLBR4PlusWorkingRegisters.CartesianPositionCommandRegister),
                operation2Operands);

            return new State(
                (int)LBR4.ControlModes.CartesianImpedanceControlMode,
                operationsList,
                new Transition[0],
                new Transition[0]);
        }

        /// <summary>
        /// Builds the controller state machine used by this controller.
        /// </summary>
        /// <returns>A controller state machine.</returns>
        protected override ControllerStateMachine BuildControllerStateMachine()
        {
            const int SynchonizationState = 0;
            const int CartesianInterplationState = 1;

            ControllerStateMachine csm = new ControllerStateMachine();

            State[] stateArray = new State[2];

            stateArray[SynchonizationState] =
                BuildSynchronizeFRICartesianPositionState();

            stateArray[CartesianInterplationState] =
                BuildSimpleCartesianInterpolationState(
                    commandedCartesianPositionResultRegister:
                        this.commandedCartesianPositionResultRegister,
                    desiredCartesianPositionRegister:
                        this.desiredCartesianPositionRegister,
                    maxLinearSpeedRegister:
                        this.maxLinearSpeedRegister,
                    maxRotationalSpeedRegister:
                        this.maxRotationalSpeedRegister,
                    cycleTimeInMsRegister:
                        this.cycleTimeInMsRegister);
            
            csm.States = new List<State>(stateArray);
                    
            // create a transition from the synchronizatino state to the interpolation state when
            // the state of the FRI connection reaches the desired value in Scalar1 (typically 2,
            // as this indicates command state -- a FRI error will result if we transition to the
            // interpolation state when the FRI connection is not in the CMD state).
            RegisterID[] transitionOnFriCmdOperands = new RegisterID[2];
            transitionOnFriCmdOperands[0] =
                this.friCmdStateValueRegister;
            transitionOnFriCmdOperands[1] = 
                RegisterID.NewFeedbackRegister((int)LBR4.KukaLBR4PlusFeedbackRegisters.FRIStateRegister);
           
            csm.States[SynchonizationState].TransitionsToEvaluateAfterDefaults = new Transition[1];

            csm.States[SynchonizationState].TransitionsToEvaluateAfterDefaults[0] = new Transition(
                csm.States[CartesianInterplationState],
                (int)LBR4.KukaLBR4Operations.AreScalarsEqualOp,
                transitionOnFriCmdOperands,
                new ControllerOperation[0]);

            return csm;
        }
    }
}
